package com.lz.ccjdemo.base;

import android.arch.lifecycle.ViewModelProvider;
import android.support.v7.app.AppCompatActivity;

import com.lz.ccjdemo.http.model.BaseModel;
import com.lz.ccjdemo.utils.ClassUtil;

public class BaseActivity<VM extends BaseModel> extends AppCompatActivity {
    // ViewModel
    protected VM viewModel;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initViewModel();
    }

    private void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            this.viewModel = new ViewModelProvider(this,
                    ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(viewModelClass);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消网络请求观察响应
        if (viewModel != null) {
            viewModel.onCleared();
        }
    }
}
